package com.volunteer.controller.admin;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.volunteer.common.R;
import com.volunteer.entity.Activity;
import com.volunteer.entity.Registration;
import com.volunteer.entity.User;
import com.volunteer.service.ActivityService;
import com.volunteer.service.RegistrationService;
import com.volunteer.service.UserService;
import lombok.AllArgsConstructor;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;

import java.time.LocalDateTime;
import java.util.List;
import java.util.Map;
import java.util.function.Function;
import java.util.stream.Collectors;

@RestController
@RequestMapping("/api/admin/registration")
@AllArgsConstructor
public class AdminRegistrationController {

    private final RegistrationService registrationService;

    private final UserService userService;

    private final ActivityService activityService;

    /**
     * 获取报名列表（分页）
     */
    @GetMapping("/list")
    public R<Page<Registration>> list(
            @RequestParam(defaultValue = "1") int pageNum,
            @RequestParam(defaultValue = "10") int pageSize,
            @RequestParam(required = false) String keyword,
            @RequestParam(required = false) Integer status) {

        LambdaQueryWrapper<Registration> queryWrapper = new LambdaQueryWrapper<>();

        // 如果有关键字，则搜索活动ID
        if (StringUtils.hasText(keyword)) {
            queryWrapper.like(Registration::getActivityId, keyword);
        }

        // 如果指定了状态，则按状态筛选
        if (status != null) {
            queryWrapper.eq(Registration::getStatus, status);
        }

        // 按报名时间倒序排序
        queryWrapper.orderByDesc(Registration::getRegisterTime);

        Page<Registration> page = registrationService.page(
            new Page<>(pageNum, pageSize),
            queryWrapper
        );
        List<Registration> records = page.getRecords();
        if (records.isEmpty()){
            return R.ok(new Page<>());
        }
        List<Long> userIds = records.stream().map(Registration::getUserId).toList();
        List<Long> activityIds = records.stream().map(Registration::getActivityId).toList();
        List<Activity> activities = activityService.listByIds(activityIds);
        List<User> users = userService.listByIds(userIds);
        Map<Long, User> map = users.stream().collect(Collectors.toMap(User::getId, Function.identity()));
        Map<Long, Activity> activityMap = activities.stream().collect(Collectors.toMap(Activity::getId, Function.identity()));

        for (Registration registration : records) {
            User user = map.get(registration.getUserId());
            if (user != null) {
                registration.setUserName(user.getName());
            }
            Activity activity = activityMap.get(registration.getActivityId());
            if (activity != null) {
                registration.setActivityName(activity.getTitle());
            }
        }
        return R.ok(page);
    }

    /**
     * 审核通过报名
     */
    @PostMapping("/approve/{id}")
    public R<String> approve(@PathVariable Long id) {
        Registration registration = new Registration();
        registration.setId(id);
        registration.setStatus(1); // 1-已通过
        registration.setAuditTime(LocalDateTime.now());
        boolean success = registrationService.updateById(registration);
        return success ? R.ok("审核通过成功") : R.fail("审核失败");
    }

    /**
     * 拒绝报名
     */
    @PostMapping("/reject/{id}")
    public R<String> reject(@PathVariable Long id, @RequestParam(required = false) String remark) {
        Registration registration = new Registration();
        registration.setId(id);
        registration.setStatus(2); // 2-已拒绝
        registration.setAuditTime(LocalDateTime.now());
        if (StringUtils.hasText(remark)) {
            registration.setAuditRemark(remark);
        }
        boolean success = registrationService.updateById(registration);
        return success ? R.ok("已拒绝该报名") : R.fail("操作失败");
    }

    /**
     * 根据ID获取报名详情
     */
    @GetMapping("/get/{id}")
    public R<Registration> getById(@PathVariable Long id) {
        Registration registration = registrationService.getById(id);
        return registration != null ? R.ok(registration) : R.fail("未找到该报名记录");
    }
}
